<!-- 车辆违章 -->
<template>
  <div class="page-container">
    <list-quick-navigation ref="listQuickNavigationRef" @change="quickNavigationChange" />
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <template #table-summary>
        <div>
          <span class="total-item">
            总罚分：<span class="num">{{ objectFieldInfo?.totalEventScore || '-' }}</span>
          </span>
          <span class="total-item">
            总罚款：<span class="num">{{ unitVal(Number(objectFieldInfo?.totalEventAmount), '元') }}</span>
          </span>
          <span class="total-item">
            待处理罚分：<span class="num">{{ objectFieldInfo?.notDealEventScore || '-' }}</span>
          </span>
          <span class="total-item">
            待处理罚款：<span class="num">{{ unitVal(Number(objectFieldInfo?.notDealEventAmount), '元') }}</span>
          </span>
          <span class="total-item">
            已处理罚分：<span class="num">{{ objectFieldInfo?.dealEventScore || '-' }}</span>
          </span>
          <span class="total-item">
            已处理罚款：<span class="num">{{ unitVal(Number(objectFieldInfo?.dealEventAmount), '元') }}</span>
          </span>
        </div>
      </template>
      <template #violantionCode="{ record }">
        <div>{{ record.violantionCode }}</div>
        <template v-if="record.violationLabelList && record.violationLabelList.length > 0">
          <tag type="primary" v-for="(item, index) in record.violationLabelList" :key="index">
            {{ item }}
          </tag>
        </template>
      </template>
      <template #urgePayStatus="{ record }">
        <urgepayStatusCell :record="record" @viewCallRecord="viewCallRecord(record)" />
      </template>
      <template #orderCodeLike="{ record }">
        <template v-if="!record.orderCode && !record.giveStaffName"> - </template>
        <template v-else>
          <template v-if="record.orderCode">
            <a-link type="link" @click="() => onLink(record)" style="color: rgba(24, 144, 255, 1)">
              {{ record.orderCode }}
            </a-link>
          </template>
          <div v-else>-</div>
          <div>交车人：{{ record.giveStaffName || '-' }}</div>
          <div>违章押金收取方式：{{ record.violationChargeTypeName || '-' }}</div>
        </template>
      </template>
      <template #memberName="{ record }">
        <div v-if="record.memberName">
          <div>{{ record.memberName }}</div>
          <div>{{ record.memberPhone }}</div>
        </div>
      </template>
      <template #createTimeAndName="{ record }">
        <p>{{ record.createTime }}</p>
        <p>{{ record.createUser }}</p>
      </template>
    </table-index>
  </div>
  <!-- 导入 -->
  <import-modal ref="imoportRef" action="/violation/importExcel" download-import="/违章管理导入模板.xlsx" @ok="loadData" />
  <!-- 催缴记录 -->
  <callRecord ref="call_record" />
  <!-- 催缴 -->
  <call ref="call_" @ok="loadData()" />
  <!-- 行驶证记录 -->
  <driving-record ref="drivingRecordRef" @ok="loadData()" />
  <!-- 自定义标签 -->
  <custom-tag-modal v-model="customTagVisible" ref="customTagRef" @ok="loadData()" />
</template>

<script setup name="CarViolationList" lang="ts">
  import call from './call/call.vue'
  import callRecord from './call/callRecord.vue'
  import listQuickNavigation from './components/list-quick-navigation.vue'
  import drivingRecord from './components/driving-record.vue'
  import customTagModal from './components/custom-tag-modal.vue'
  import urgepayStatusCell from './components/urgepay-status-cell.vue'

  import { ref, reactive, onMounted, computed, onActivated } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { usePageDict } from '@/hooks/useDict'
  import {
    getList,
    exportViolation,
    getViolationStatistics,
    closeViolation,
    getViolationDetail,
    delViolation,
  } from '@/api/asset/carViolation'
  import { useExport } from '@/hooks/list'
  import useNavigate from '@/hooks/useNavigate'
  import { useRoute } from 'vue-router'
  import { unitVal } from '@/utils'
  import { Modal, Notification } from '@arco-design/web-vue'

  const route = useRoute()
  const { navigateTo, registerListHotUpdate, navigateToCreate } = useNavigate()

  const imoportRef = ref()
  const dict = usePageDict('carviolationDict')

  const queryParam = reactive<any>({
    queryDate: [],
    queryCreateTimeDate: [],
  })

  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车牌号', prop: 'licenseNoLike', type: 'a-input' },
      {
        label: '车辆当前归属门店',
        prop: 'carSiteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
        },
      },
      { label: '违章状态', prop: 'eventStatusList', type: 'a-select', multiple: true, options: dict.ViolationEventStatusEnum },
      { label: '催缴状态', prop: 'urgePayStatus', type: 'a-select', options: dict.urgePayStatus },
      {
        label: '违章单关联门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
        },
      },
      { label: '违章单号', prop: 'violationCodeLike', type: 'a-input' },
      {
        label: '违章周期',
        prop: 'queryDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.eventTimeStart = value[0]
          queryParam.eventTimeEnd = value[1]
        },
      },
      { label: '处理方', prop: 'handleType', type: 'a-select', options: dict.violationHandleEnum },
      {
        label: '负责人',
        prop: 'staffIdList',
        type: 'remote-select',
        attrs: {
          type: 'staff_authOrg_multiple',
        },
      },
      { label: '车架号', prop: 'vin', type: 'a-input' },
      { label: '关联单号', prop: 'orderCodeLike', type: 'a-input' },
      {
        label: '订单渠道',
        prop: 'channelType',
        type: 'sysdict-select',
        attrs: { code: 'short_order_channel_type' },
        addable: false,
      },
      {
        label: '交车人',
        prop: 'giveStaffId',
        type: 'remote-select',
        attrs: {
          type: 'store_staff_list',
        },
      },
      {
        label: '承租人',
        prop: 'memberName',
        type: 'a-input',
      },
      { label: '费用状态', prop: 'violationFeeStateList', type: 'a-select', multiple: true, options: dict.violationFeeStateEnum },
      { label: '违章发生方', prop: 'violationParty', type: 'a-select', options: dict.violationPartyEnum },
      { label: '违章标签', prop: 'violationLabel', type: 'a-select', options: dict.violationLabelEnum },
      {
        label: '违章押金收取方式',
        prop: 'violationChargeTypeList',
        type: 'a-select',
        multiple: true,
        options: dict.inExpWayList,
      },
      {
        label: '创建时间',
        prop: 'queryCreateTimeDate',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        change: (value = []) => {
          queryParam.createTimeStart = value[0]
          queryParam.createTimeEnd = value[1]
        },
      },
      { label: '创建人', prop: 'createUserNameLike', type: 'a-input', maxlength: 20 },
      { label: '违章查询状态', prop: 'queryStatusList', multiple: true, type: 'a-select', options: dict.violationQueryStatusEnum },
    ]
  })

  // 获取行驶证信息
  const getDrivingData = (record: any) => {
    return new Promise((resolve, reject) => {
      getViolationDetail({ id: record.id })
        .then((res: any) => {
          resolve(res.result)
        })
        .catch((err: any) => {
          reject(err)
        })
    })
  }

  const drivingRecordRef = ref()
  const customTagVisible = ref(false)
  const customTagRef = ref()
  // table 配置
  const table = useTable({
    queryParam,
    columns: [
      { title: '车牌号', dataIndex: 'licenseNo', fixed: 'left' },
      {
        title: '违章时间',
        dataIndex: 'eventTime',
        sortable: { sortDirections: ['ascend', 'descend'] },
        width: 170,
      },
      { title: '承租人信息', dataIndex: 'memberName', slotName: 'memberName', width: 120 },
      { title: '罚分', dataIndex: 'eventScore', width: 60 },
      { title: '罚款', dataIndex: 'eventAmount', unit: '元', width: 80 },
      { title: '违章状态', dataIndex: 'eventStatusStr', width: 90 },
      { title: '违章查询状态', dataIndex: 'violationQueryStatusName', width: 110 },
      { title: '催缴状态', dataIndex: 'urgePayStatusName', slotName: 'urgePayStatus', width: 90 },
      { title: '违章发生方', dataIndex: 'violationPartyName', width: 100 },
      { title: '违章城市', dataIndex: 'eventCityName', width: 90 },
      { title: '处理方', dataIndex: 'handleTypeName', width: 90 },
      {
        title: '违章代办收入',
        dataIndex: 'incomeAmount',
        titleTooltipContent: '违章代办收入=代办费用-代办真实成本',
        unit: '元',
        width: 160,
      },
      { title: '代办费用', dataIndex: 'handleAmount', unit: '元', width: 110 },
      { title: '违章代办真实成本', dataIndex: 'handleRealCost', unit: '元', width: 170 },
      { title: '费用状态', dataIndex: 'violationFeeStateName', width: 90 },
      { title: '负责人', dataIndex: 'staffName', width: 80 },
      { title: '创建时间及创建人', slotName: 'createTimeAndName', width: 170 },
      { title: '订单渠道', dataIndex: 'orderChannelName', width: 100 },
      { title: '关联单号', dataIndex: 'orderCode', slotName: 'orderCodeLike', width: 240 },
      { title: '违章单号', dataIndex: 'violantionCode', slotName: 'violantionCode', width: 140 },
    ],
    operates: [
      /**
       * 违章状态 eventStatus: 0 未处理 1 已处理 3 已关闭
       * 费用状态 violationFeeState: 1 无需收款 2 未收款 3 已收款
       * 处理方 handleType: 1 租车公司 2 客户处理 3 员工处理
       */
      {
        label: '详情',
        permission: 'svms:asstes:operation:car-violation.detail',
        method: (record: any) => {
          navigateTo(`/car-violation/detail/${record.id}?handleType=${record.handleType}`, `${record.licenseNo}-违章详情`)
        },
      },
      {
        label: '编辑',
        permission: 'svms:asstes:operation:car-violation.edit',
        // 状态为【待处理】时，支持编辑
        show: (record: any) => record.eventStatus === 0 || record.eventStatus === 1,
        method: (record: any) => {
          if (record.eventStatus === 1) {
            navigateTo(`/car-violation/edit/${record.id}?page=violationEnd`, `${record.licenseNo}-违章编辑`)
          } else {
            navigateTo(`/car-violation/edit/${record.id}`, `${record.licenseNo}-违章编辑`)
          }
        },
      },
      {
        label: '处理完成',
        permission: 'svms:asstes:operation:car-violation.handling',
        // 状态为【待处理】时，展示该按钮
        show: (record: any) => record.eventStatus === 0,
        method: (record: any) => {
          navigateTo(`/car-violation/edit/${record.id}?page=violation`, `${record.licenseNo}-处理完成`)
        },
      },
      {
        label: '确认/修改费用',
        show: (record: any) => record.eventStatus !== 3 && record.violationFeeState !== 1 && record.handleType == 1,
        permission: 'svms:asstes:operation:car-violation.fee',
        method: (record: any) => {
          navigateTo(`/car-violation/detail/${record.id}?tab=2&handleType=${record.handleType}`, `${record.licenseNo}-违章详情`)
        },
      },
      {
        label: '催缴',
        // 违章状态为待处理、催缴状态为待催缴、已催缴时，支持【催缴】操作
        // 0812 都支持
        // show: (record) => record.eventStatus == 0,
        permission: 'svms:asstes:operation:car-violation.call',
        method: (record: any) => handleCall(record),
      },
      {
        label: '关闭',
        permission: 'svms:asstes:car:car-violation.close',
        show: (record: any) => record.status == 0 || record.status == 1,
        method: (record: any) => {
          Modal.confirm({
            title: '关闭违章单',
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content: '关闭后，不支持恢复，是否确认关闭？',
            onOk: () => {
              closeViolation({ id: record.id }).then(() => {
                Notification.success({
                  content: '关闭成功',
                  closable: true,
                  duration: 3000,
                })
                loadData()
              })
            },
          })
        },
      },
      {
        label: '行驶证记录',
        // permission: 'svms:asstes:operation:car-violation.drivingrecord', // 不受权限控制，保留后续添加方便
        show: (record: any) => record.eventStatus !== 3 && record.violationFeeState == 1 && record.handleType !== 1,
        method: (record: any) => {
          getDrivingData(record).then((res) => {
            drivingRecordRef.value.open(res)
          })
        },
      },
      {
        label: '添加标签',
        permission: 'svms:asstes:operation:car-violation.addlabel',
        show: (record: any) => record.eventStatus !== 3,
        method: (record: any) => {
          customTagVisible.value = true
          customTagRef.value.open(record)
        },
      },
      {
        label: '操作记录',
        permission: 'svms:asstes:operation:car-violation.operaterecords',
        method: (record: any) => {
          navigateTo(
            `/car-violation/detail/${record.id}?eventStatus=${record.eventStatus}&handleType=${record.handleType}&tab=3`,
            `${record.licenseNo}-操作记录`
          )
        },
      },
      {
        label: '删除',
        permission: 'svms:asstes:operation:car-violation.delete',
        method: (record: any) => {
          if (record.ifPay || record.eventStatus == 1) {
            Modal.error({
              title: '不支持删除',
              content: '当违章状态为未处理，且关联的费用为未收/付款时，支持删除',
            })
          } else {
            Modal.confirm({
              title: '删除违章单',
              simple: true,
              cancelText: '取消',
              okText: '确认',
              bodyStyle: {
                'text-align': 'center',
              },
              content: '删除后，不支持恢复，是否确认删除？',
              onOk: () => {
                delViolation({ id: record.id }).then(() => {
                  Notification.success({
                    content: '删除成功',
                    closable: true,
                    duration: 3000,
                  })
                  loadData()
                })
              },
            })
          }
        },
      },
    ],
    buttons: [
      {
        mode: 'import',
        label: '导入',
        permission: 'svms:asstes:operation:car-violation.import',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        mode: 'export',
        label: '导出',
        permission: 'svms:asstes:operation:car-violation.export',
        method: () => handleExport(),
      },
      {
        type: 'primary',
        icon: 'plus',
        label: '新增',
        permission: 'svms:asstes:operation:car-violation.create',
        method: () => {
          navigateToCreate('/car-violation/create')
        },
      },
    ],
  })

  const onLink = (record: any) => {
    if (record.eventType == 4) {
      navigateTo(`/short-order/detail/${record.orderId}`, `${record.orderCode}-短租详情`)
    } else if (record.eventType == 7) {
      navigateTo(`/long-order/detail/${record.orderId}`, `${record.orderCode}-长租详情`)
    }
  }

  const listQuickNavigationRef = ref()
  // 列表接口调用
  const loadData = (page?: any, type?: any) => {
    if (type === 'reset') {
      queryParam.handlePayStatus = undefined
    }
    const fn = useFetchTableDataApi(table, queryParam, getList)
    fn(page).then((res: any) => {
      res.data.forEach((item: any) => {
        if (item.violationLabelIds) {
          item.violationLabelIds = item.violationLabelIds?.split(',').map((tempItem: any) => +tempItem)
        } else {
          item.violationLabelIds = []
        }
      })
    })
    // before 刷新顶部快捷筛选数据、list-searcher刷新重置 重置快捷筛选
    if (type == 'reset' || type == 'submit') {
      listQuickNavigationRef.value.reset()
    }
    if (type != 'onlyLoadList') {
      getViolationStatisticsFn()
      listQuickNavigationRef.value.getStNum()
    }
    // end
  }

  // 快捷导航点击事件
  const quickNavigationChange = (param: any) => {
    // 清空
    for (var k in queryParam) {
      queryParam[k] = undefined
    }
    // 更新数据
    for (var k in param) {
      queryParam[k] = param[k]
    }
    loadData(1, 'quickNavigation')
  }

  // 导出事件
  const handleExport = () => {
    useExport(exportViolation, queryParam)
  }

  // 统计
  const objectFieldInfo = ref()
  const getViolationStatisticsFn = () => {
    getViolationStatistics(queryParam).then((res: any) => {
      const { result } = res
      objectFieldInfo.value = result
    })
  }

  // 查看催缴记录
  const call_record = ref()
  const viewCallRecord = (record: any) => {
    console.log(record)
    call_record.value.show(record.id)
  }
  // 催缴
  const call_ = ref()
  const handleCall = (record: any) => {
    call_.value.show(record)
  }

  // 初始化参数&加载list
  const initParamsLoadData = () => {
    if (route.query && route.query.source == 'inpect') {
      queryParam.licenseNoLike = route.query.licenseNo
      queryParam.eventStatusList = [0]
    }
    if (route.query?.id) {
      queryParam.eventStatusList = [+route.query.id]
    }
    loadData(1, 'onlyLoadList')
  }
  // 监听路由变化，更新快捷导航数量
  onActivated(() => {
    listQuickNavigationRef.value.getStNum()
    getViolationStatisticsFn()
  })

  onMounted(() => {
    initParamsLoadData()
    // 注册热更新
    registerListHotUpdate(() => loadData(undefined, 'onlyLoadList'))
  })
</script>

<style lang="less" scoped>
  .total-item {
    margin-right: 20px;
    .num {
      color: #1890ff;
    }
  }
</style>
